package com.hxzy.jsp.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 获取数据库连接工具类
 * 
 * @author Administrator
 *
 */
public final class Connections {
	private static ThreadLocal<Connection> connectionHolder = new ThreadLocal<>();

	public static Connection get() {
		if (connectionHolder.get() != null) {
			return connectionHolder.get();
		}

		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(String.format("数据库驱动加载失败：%s", e.getMessage()));
		}

		try {
			String url = String.format(
					"jdbc:mysql://%s:%d/%s?user=%s&password=%s&useUnicode=true&characterEncoding=%s&useSSL=false",
					"172.16.1.55", 3306, "stu_bbs", "chenghaojun", "123456", "UTF8");
			connectionHolder.set(DriverManager.getConnection(url));
		} catch (Exception e) {
			throw new RuntimeException("创建连接失败：".concat(e.getMessage()));
		}

		return connectionHolder.get();

	}

	public static void close() {
		if (connectionHolder.get() != null) {
			try {
				connectionHolder.get().close();
			} catch (SQLException e) {
				throw new RuntimeException("关闭连接失败：".concat(e.getMessage()));
			}
		}
	}

	/**
	 * 获取一个新的数据库连接，由调用方负责关闭数据库连接
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		return get();
	}

}
